import numpy as np
from network import QKDNetwork
from generate import GenerateNetwork
from rounding import solver
from compare import onlineGreedy, spf, cplexResult
from lp_create_matrix import clear_lp_matrix, get_lp_matrix
from log import clearContent, addContent

def print_progressbar(iteration, total, prefix='', suffix='', decimals=1, length=50, fill='█'):
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filled_length = int(length * iteration // total)
    bar = fill * filled_length + '-' * (length - filled_length)
    print(f'\r{prefix} |{bar}| {percent}% {suffix}', end='\r')
    if iteration == total:
        print(
            "\r                                                                                                                                                   ",
            end='\r')

# with open("./analysis_data/cplex_progress.txt", 'w') as file:
#     file.write('')
clearContent("log.txt")

start = 4
end = 5 # 5 --> 15 个节点

# 最后返回的结果 (key: 5 --> 15 个节点) 
# {
#     5: [[] * 9],
#     6: [[] * 9],
#     ...
# }
result_data_map = {key: [[] for _ in range(9)] for key in range(start, end)}

# 计算均值函数
def calculate_mean(lst):
    return sum(lst) / len(lst) if lst else 0

def getMeanMap():
    # 生成新的字典，其中包含均值
    mean_data_map = {
        key: [calculate_mean(sublist) for sublist in sublists]
        for key, sublists in result_data_map.items()
    }
    return mean_data_map

def run():
    for _ in range(1):
        for i in range(start, end):
            SPF_total = 0
            SPF_RU_total = 0
            SPF_Jindex_total = 0
            OnlineGreedy_total = 0
            OnlineGreedy_RU_total = 0
            OnlineGreedy_Jindex_total = 0
            Cplex_total = 0
            Cplex_RU_total = 0
            Cplex_Jindex_total = 0
            round_num = 1
            alpha_start = 1.25
            alpha_decrease = 0.035
            try:
                for j in range(round_num):
                    numNodes = i
                    alpha = alpha_start - numNodes * alpha_decrease
                    beta = 0.1
                    seed = j
                    # GenerateNetwork.generate_network(numNodes, alpha, beta, seed) # 生成一个网络
                    n = QKDNetwork("generate.txt")
                    x_ret, p_ret, _ = solver(n, len(n.nodeList), {'alpha': alpha, 'beta': beta, 'seed': 1})

                    total_spf_alpha = []
                    total_spf_ru = []
                    total_spf_jidx = []

                    total_online_greedy_alpha = []
                    total_online_greedy_ru = []
                    total_online_greedy_jidx = []

                    total_cplex_alpha = []
                    total_cplex_ru = []
                    total_cplex_jidx = []
                    
                    matrix_round_num = 50
                    for k in range(matrix_round_num):  # 迭代100轮 求100个业务量矩阵的最大值
                        if (k == matrix_round_num - 1):
                            outfile = open("./analysis_data/cplex_progress.txt", "+a")
                            outfile.write(f'Node:{numNodes}  Alpha:{round(alpha, 2)}  Round:{j + 1}/{round_num}\n')
                            outfile.close()
                        # print_progressbar(k + 1, matrix_round_num, f'Node:{numNodes} Alpha:{round(alpha, 2)}',f' {j + 1}/{round_num}')
                        matrix_experiment = get_lp_matrix(n)
                        online_greedy_alpha, online_greedy_resource_utilization, online_greedy_jindex = onlineGreedy(n, matrix_experiment)
                        spf_alpha, spf_resource_utilization, spf_jindex = spf(n, matrix_experiment)
                        cplex_alpha, cplex_resource_utilization, cplex_jindex = cplexResult(n, matrix_experiment, x_ret, p_ret)

                        total_cplex_alpha.append(cplex_alpha)
                        total_cplex_ru.append(cplex_resource_utilization)
                        total_cplex_jidx.append(cplex_jindex)

                        total_online_greedy_alpha.append(online_greedy_alpha)
                        total_online_greedy_ru.append(online_greedy_resource_utilization)
                        total_online_greedy_jidx.append(online_greedy_jindex)

                        total_spf_alpha.append(spf_alpha)
                        total_spf_ru.append(spf_resource_utilization)
                        total_spf_jidx.append(spf_jindex)
                    SPF_total += np.mean(total_spf_alpha)
                    SPF_RU_total += np.mean(total_spf_ru)
                    SPF_Jindex_total += np.mean(total_spf_jidx)

                    OnlineGreedy_total += np.mean(total_online_greedy_alpha)
                    OnlineGreedy_RU_total += np.mean(total_online_greedy_ru)
                    OnlineGreedy_Jindex_total += np.mean(total_online_greedy_jidx)

                    Cplex_total += np.mean(total_cplex_alpha)
                    Cplex_RU_total += np.mean(total_cplex_ru)
                    Cplex_Jindex_total += np.mean(total_cplex_jidx)
                    clear_lp_matrix(numNodes)
                addContent("log.txt", f"nodeNum: {i} Aplha: {alpha_start - i * alpha_decrease}")
                # 打印参数信息
                addContent("log.txt", f"SPF: {SPF_total / round_num}")
                result_data_map[i][0].append(SPF_total / round_num)
                addContent("log.txt", f"Online: {OnlineGreedy_total / round_num}")
                result_data_map[i][1].append(OnlineGreedy_total / round_num)
                addContent("log.txt", f"Cplex: {Cplex_total / round_num}")
                result_data_map[i][2].append(Cplex_total / round_num)

                addContent("log.txt", f"SPF_RU: {SPF_RU_total / round_num}")
                result_data_map[i][3].append(SPF_RU_total / round_num)
                addContent("log.txt", f"Online_RU: {OnlineGreedy_RU_total / round_num}")
                result_data_map[i][4].append(OnlineGreedy_RU_total / round_num)
                addContent("log.txt", f"Cplex_RU: {Cplex_RU_total / round_num}")
                result_data_map[i][5].append(Cplex_RU_total / round_num)

                addContent("log.txt", f"SPF_Jindex: {SPF_Jindex_total / round_num}")
                result_data_map[i][6].append(SPF_Jindex_total / round_num)
                addContent("log.txt", f"Online_Jindex: {OnlineGreedy_Jindex_total / round_num}")
                result_data_map[i][7].append(OnlineGreedy_Jindex_total / round_num)
                addContent("log.txt", f"Cplex_Jindex: {Cplex_Jindex_total / round_num}")
                result_data_map[i][8].append(Cplex_Jindex_total / round_num)


                clearContent("log_pure.txt")
                for tmp_i in range(start, end):
                    for tmp_j in range(9):
                        addContent("log_pure.txt", f"{getMeanMap()[tmp_i][tmp_j]}")
                        # print(f"numNodes:{numNodes}  i:{tmp_i}  j:{tmp_j}  {getMeanMap()[tmp_i][tmp_j]}")

                addContent("log_pure.txt", f"{getMeanMap()}")

                # addContent("log.txt", f"Optimal: {alpha_ret}")
                # print(f"nodeNum：{i} Aplha：{alpha_start - i * alpha_decrease}")
                # print("SPF：", SPF_total / round_num)
                # print("Cplex：", Cplex_total / round_num)
            except:
                print("有错，但是不管")


run()
